#include "pch.hpp"

#include "animation.h"

void animation::load(std::string path, int spriteWidth, int spriteHeight, int frmCnt,
	int intrval, bool loop, float scale)
{
	fScale = scale;
	position = sf::Vector2f(0,0);
	frameCnt = frmCnt;
	interval = intrval;
	looped = loop;
	color = sf::Color(255,255,255,255);
	rotation = 0;

	spriteSheet.LoadFromFile(path);
	int rowCnt = spriteSheet.GetWidth() / spriteWidth; //frames per row
	int curCnt = 0; 

	frames.clear();

	for(int i = 0; curCnt < frameCnt; ++i)
		for(int j = 0; j < rowCnt && curCnt < frameCnt; ++j)
		{
			frames.push_back(sf::Sprite());
			frames.back().SetImage(spriteSheet);
			frames.back().SetSubRect(sf::IntRect(j * spriteWidth, i * spriteHeight, (j + 1) * spriteWidth, (i + 1) * spriteHeight));
			frames.back().SetCenter(spriteWidth / 2,spriteHeight / 2);

			++curCnt;
		}
}

bool animation::draw(int time)
{
	return draw(time, sf::Vector2f(0, -1));
}

bool animation::draw(int time, sf::Vector2f dir) //time in miliseconds
{
	bool res = false;

	if(looped && time >= frames.size() * interval)
		time %= frames.size() * interval;
	else if(!looped && time >= frames.size() * interval) //pause on the last frame
	{	
		time = frames.size() * interval - 1;
		res = true;
	}

	int idx = (time / float(frames.size() * interval)) * frameCnt;
	
	frames[idx].SetPosition(position);
	frames[idx].SetColor(color);
	if(dir.x == dir.y && dir.x == 0)
		frames[idx].SetRotation(rotation);
	else
		directToVector(frames[idx], dir);
	frames[idx].SetScale(fScale, fScale);
	app.Draw(frames[idx]);

	return res;
}

void animation::SetPos(sf::Vector2f pos)
{
	position = pos;
}